package com.baitiaojun.xss.config;

import com.baitiaojun.common.constants.WebFilterOrderEnum;
import com.baitiaojun.xss.core.filter.ServletRequestXssFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.DispatcherType;

//enable条件为true的时候开启配置
@ConditionalOnProperty(prefix = "xss", name = "enable", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(XssProperties.class)
@AutoConfiguration
public class XssAutoConfiguration {

    @Autowired
    private XssProperties xssProperties;
    
    @Bean
    public FilterRegistrationBean<ServletRequestXssFilter> servletRequestXssFilter() {
        FilterRegistrationBean<ServletRequestXssFilter> filterRegistrationBean
                = new FilterRegistrationBean<>(new ServletRequestXssFilter(xssProperties));
        filterRegistrationBean.setOrder(WebFilterOrderEnum.XSS_FILTER);
        filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST); //当浏览器直接请求服务器时, 会执行xss过滤
        return filterRegistrationBean;
    }
}
